package com.longchain.business.search;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hh.base.MyUtils;
import com.hh.base.log.SLog;
import com.hh.base.util.UIUtil;
import com.hjy.http.download.DownloadManager;
import com.hjy.http.download.FileDownloadTask;
import com.hjy.http.download.listener.OnDownloadingListener;
import com.longchain.R;
import com.longchain.common.base.BaseFragment;
import com.longchain.common.widget.BottomFileOperationLayout;
import com.longchain.manager.entity.LongChainFile;
import com.longchain.manager.entity.SeverFileEntity;
import com.longchain.manager.util.FileConvertUtils;
import com.luck.picture.lib.PicturePreviewActivity;
import com.luck.picture.lib.PictureVideoPlayActivity;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.observable.ImagesObservable;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Administrator on 2018/4/19.
 */

public abstract class BaseSearchFragment extends BaseFragment {
   private static final String TAG = "BaseSearchFragment";
   @BindView(R.id.recycler_view)
   RecyclerView mRecyclerView;

   @BindView(R.id.empty_layout)
   View mEmptyLayout;

   @BindView(R.id.empty_image)
   ImageView mEmptyImage;

   @BindView(R.id.empty_text)
   TextView mEmptyText;

   @BindView(R.id.bottom_layout)
   BottomFileOperationLayout mBottomLayout;

   FileAdapter mAdapter;
   List<SeverFileEntity> mDatas;


   @Override
   protected int setLayoutResourceID() {
      return R.layout.search_all_fragment;
   }

   @Override
   protected void setUpView() {
      final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
      layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
      mRecyclerView.setLayoutManager(layoutManager);
      mAdapter = new FileAdapter(getContext(), mDatas, new FileAdapter.OnItemClick() {

         @Override
         public void onItemClick(int position) {

             List<SeverFileEntity> images = mAdapter.mDatas;
             List<LocalMedia> localMediaList = FileConvertUtils.getLocalMediaList(images);
             startPreview(localMediaList, position);
         }
      });
      mBottomLayout.setOnOperationListener(new BottomFileOperationLayout.OnOperation() {
         @Override
         public void onDeleteClick() {

             final List<SeverFileEntity> selectedImages = mAdapter.getSelectedImages();
                if (selectedImages != null && selectedImages.size() > 0) {
                   UIUtil.showConfirmDialog(getContext(), "确定删除文件？", "确定删除后文件不可恢复", new View.OnClickListener() {
                      @Override
                      public void onClick(View view) {
                         for (SeverFileEntity localMedia : selectedImages) {
                            mDatas.remove(localMedia);
                         }
                         mAdapter.setmDatas(mDatas);
                      }
                   },"取消","确定");
                } else {
                    UIUtil.showToast("请先选中要删除的文件");
                }


         }

         @Override
         public void onDownLoadClick() {
            UIUtil.showToast("已保存到相册");

             List<SeverFileEntity> list = mAdapter.getSelectedImages();

             if (list!=null && list.size()!=0){

                 for (SeverFileEntity fileEntity :list){

                     DownloadManager.getInstance(getContext()).downloadFile(PictureMimeType.ofAll(), String.valueOf(fileEntity.getFile_id()),
                             MyUtils.HOST+fileEntity.getUrl(), new OnDownloadingListener() {
                                 @Override
                                 public void onDownloadFailed(FileDownloadTask task, int errorType, String msg) {

                                     SLog.e(TAG, "download faild" + errorType + msg);
                                 }

                                 @Override
                                 public void onDownloadSucc(FileDownloadTask task, File outFile) {
                                     SLog.d(TAG, "download success! file path "+outFile.getAbsolutePath());

                                     UIUtil.showToast("下载成功，文件路径："+outFile.getAbsolutePath());


                                 }
                             });

                 }

             }


         }

         @Override
         public void onEditTagClick() {

         }
      });
      mRecyclerView.setAdapter(mAdapter);
   }

   @Override
   protected void setUpData() {

   }

    public void startPreview(List<LocalMedia> previewImages, int position) {
        LocalMedia media = previewImages.get(position);
        String pictureType = media.getPictureType();
        Bundle bundle = new Bundle();
        List<LocalMedia> result = new ArrayList<>();
        int mediaType = PictureMimeType.isPictureType(pictureType);
        switch (mediaType) {
            case PictureConfig.TYPE_IMAGE:
                // image
                List<LocalMedia> selectedImages = new ArrayList<>();
                ImagesObservable.getInstance().saveLocalMedia(previewImages);
                bundle.putSerializable(PictureConfig.EXTRA_SELECT_LIST, (Serializable) selectedImages);
                bundle.putInt(PictureConfig.EXTRA_POSITION, position);
                Intent intent = new Intent();
                intent.setClass(getActivity(), PicturePreviewActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
//                overridePendingTransition(com.luck.picture.lib.R.anim.a5, 0);
                break;
            case PictureConfig.TYPE_VIDEO:
                // video
//                if (config.selectionMode == PictureConfig.SINGLE) {
//                    result.add(media);
////                    onResult(result);
//                } else {
                    bundle.putString("video_path", media.getPath());
                    Intent intent1 = new Intent();
                    intent1.setClass(getActivity(), PictureVideoPlayActivity.class);
                    intent1.putExtras(bundle);
                    startActivity(intent1);
//                }
                break;
            case PictureConfig.TYPE_AUDIO:
                // audio
               /* if (config.selectionMode == PictureConfig.SINGLE) {
                    result.add(media);
//                    onResult(result);
                } else {
//                    audioDialog(media.getPath());
                }*/
                break;
        }
    }

   public  void updateData(List<SeverFileEntity> mDatas){
      this.mDatas = mDatas;
      if (mDatas == null || mDatas.size() == 0) {
         mEmptyLayout.setVisibility(View.VISIBLE);
         mRecyclerView.setVisibility(View.GONE);
      } else {
         mEmptyLayout.setVisibility(View.GONE);
         mRecyclerView.setVisibility(View.VISIBLE);
         mAdapter.setmDatas(mDatas);
      }
   }

   public abstract String getFileType();


}
